home *** CD-ROM | disk | FTP | other *** search
/ Power Programmierung 2 / Power-Programmierung CD 2 (Tewi)(1994).iso / gnu / gnulib / ohlutil / ls.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-08-24  |  43.3 KB  |  1,963 lines

  1. /* `dir', `vdir' and `ls' directory listing programs for GNU.
  2.    Copyright (C) 1985, 1988, 1989, 1990 Free Software Foundation, Inc.
  3.    ChangeLog: changelog
  4.  
  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 1, or (at your option)
  8.    any later version.
  9.  
  10.    This program is distributed in the hope that it will be useful,
  11.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13.    GNU General Public License for more details.
  14.  
  15.    You should have received a copy of the GNU General Public License
  16.    along with this program; if not, write to the Free Software
  17.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  18.  
  19. /*
  20.  * MS-DOS port (c) 1990 by Thorsten Ohl, td12@ddagsi3.bitnet
  21.  *
  22.  * To this port, the same copying conditions apply as to the
  23.  * original release.
  24.  *
  25.  * IMPORTANT:
  26.  * This file is not identical to the original GNU release!
  27.  * You should have received this code as patch to the official
  28.  * GNU release.
  29.  *
  30.  * MORE IMPORTANT:
  31.  * This port comes with ABSOLUTELY NO WARRANTY.
  32.  *
  33.  * $Header: e:/gnu/fileutil/RCS/ls.c'v 1.3.0.2 90/06/29 00:46:51 tho Stable $
  34.  */
  35.  
  36. /* If the macro MULTI_COL is defined,
  37.    the multi-column format is the default regardless
  38.    of the type of output device.
  39.    This is for the `dir' program.
  40.  
  41.    If the macro LONG_FORMAT is defined,
  42.    the long format is the default regardless of the
  43.    type of output device.
  44.    This is for the `vdir' program.
  45.  
  46.    If neither is defined,
  47.    the output format depends on whether the output
  48.    device is a terminal.
  49.    This is for the `ls' program. */
  50.  
  51. /* Written by Richard Stallman and David MacKenzie. */
  52.  
  53. #include <sys/types.h>
  54. #ifdef _POSIX_SOURCE
  55. #define S_IEXEC S_IXUSR
  56. #else
  57. #ifdef MSDOS
  58. #include <fcntl.h>
  59. #else /* not MSDOS */
  60. #include <sys/ioctl.h>
  61. #endif /* not MSDOS */
  62. #endif
  63.  
  64. #include <stdio.h>
  65.  
  66. #ifdef MSDOS
  67. #include <malloc.h>
  68. #include <io.h>
  69. #include "msd_pwd.h"
  70. #else /* not MSDOS */
  71. #include <grp.h>
  72. #include <pwd.h>
  73. #endif /* not MSDOS */
  74.  
  75. #include "getopt.h"
  76. #include "system.h"
  77.  
  78. /* Return an int indicating the result of comparing two longs. */
  79. #ifdef INT_16_BITS
  80. #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
  81. #else
  82. #define longdiff(a, b) ((a) - (b))
  83. #endif
  84.  
  85. #ifdef STDC_HEADERS
  86. #include <errno.h>
  87. #include <stdlib.h>
  88. #include <time.h>
  89. #else
  90. char *ctime ();
  91. char *getenv ();
  92. char *malloc ();
  93. char *realloc ();
  94. long time ();
  95.  
  96. extern int errno;
  97. #endif
  98.  
  99. #ifdef MSDOS
  100. #include <string.h>
  101. extern  void mode_string (unsigned short mode, char *str);
  102. extern  int glob_match (char *, char *, int);        /* glob.c    */
  103. extern  void main (int, char **);
  104. extern  int argmatch (char *, char **);
  105. extern  int decode_switches (int, char **);
  106. extern  void invalid_arg (char *, char *, int);
  107. extern  void queue_directory (char *, char *);
  108. extern  void print_dir (char *, char *);
  109. extern  void add_ignore_pattern (char *);
  110. extern  int file_interesting (struct direct *);
  111. extern  void clear_files (void);
  112. extern  int gobble_file (char *, int, char *);
  113. extern  void extract_dirs_from_files (char *, int);
  114. extern  int is_not_dot_or_dotdot (char *);
  115. extern  void sort_files (void);
  116. extern  int compare_ctime (struct file *, struct file *);
  117. extern  int rev_cmp_ctime (struct file *, struct file *);
  118. extern  int compare_mtime (struct file *, struct file *);
  119. extern  int rev_cmp_mtime (struct file *, struct file *);
  120. extern  int compare_atime (struct file *, struct file *);
  121. extern  int rev_cmp_atime (struct file *, struct file *);
  122. extern  int compare_size (struct file *, struct file *);
  123. extern  int rev_cmp_size (struct file *, struct file *);
  124. extern  int compare_name (struct file *, struct file *);
  125. extern  int rev_cmp_name (struct file *, struct file *);
  126. extern  void print_current_files (void);
  127. extern  void print_long_format (struct file *);
  128. extern  void print_name_with_quoting (char *);
  129. extern  void print_file_name_and_frills (struct file *);
  130. extern  void print_type_indicator (unsigned int);
  131. extern  int length_of_file_name_and_frills (struct file *);
  132. extern  void print_many_per_line (void);
  133. extern  void print_horizontal (void);
  134. extern  void print_with_commas (void);
  135. extern  char *getuser (int);
  136. extern  char *getgroup (int);
  137. extern  void indent (int, int);
  138. extern  char *xrealloc (char *, int);
  139. extern  char *xmalloc (int);
  140. extern  void error (int status, int errnum, char *message, ...);
  141. extern  void perror_with_name (char *);
  142. extern  char *copystring (char *);
  143. extern  void attach (char *, char *, char *);
  144. extern  char *basename (char *);
  145. extern  void usage (void);
  146. #endif /* MSDOS */
  147.  
  148. struct group *getgrgid ();
  149. struct passwd *getpwuid ();
  150. int glob_match ();
  151. void mode_string ();
  152.  
  153. char *copystring ();
  154. char *getgroup ();
  155. char *getuser ();
  156. char *make_link_path ();
  157. char *xmalloc ();
  158. char *xrealloc ();
  159. int compare_atime ();
  160. int rev_cmp_atime ();
  161. int compare_ctime ();
  162. int rev_cmp_ctime ();
  163. int compare_mtime ();
  164. int rev_cmp_mtime ();
  165. int compare_size ();
  166. int rev_cmp_size ();
  167. int compare_name ();
  168. int rev_cmp_name ();
  169. int decode_switches ();
  170. int file_interesting ();
  171. int gobble_file ();
  172. int is_not_dot_or_dotdot ();
  173. int length_of_file_name_and_frills ();
  174. void add_ignore_pattern ();
  175. void attach ();
  176. void clear_files ();
  177. void error ();
  178. void extract_dirs_from_files ();
  179. void get_link_name ();
  180. void indent ();
  181. void invalid_arg ();
  182. void print_current_files ();
  183. void print_dir ();
  184. void print_file_name_and_frills ();
  185. void print_horizontal ();
  186. void print_long_format ();
  187. void print_many_per_line ();
  188. void print_name_with_quoting ();
  189. void print_type_indicator ();
  190. void print_with_commas ();
  191. void queue_directory ();
  192. void sort_files ();
  193. void usage ();
  194.  
  195. enum filetype
  196. {
  197.   symbolic_link,
  198.   directory,
  199.   arg_directory,        /* Directory given as command line arg. */
  200.   normal            /* All others. */
  201. };
  202.  
  203. struct file
  204. {
  205.   /* The file name. */
  206.   char *name;
  207.  
  208.   struct stat stat;
  209.  
  210.   /* For symbolic link, name of the file linked to, otherwise zero. */
  211.   char *linkname;
  212.  
  213.   /* For symbolic link and long listing, st_mode of file linked to, otherwise
  214.      zero. */
  215.   unsigned int linkmode;
  216.  
  217.   enum filetype filetype;
  218. };
  219.  
  220. /* The table of files in the current directory:
  221.  
  222.    `files' points to a vector of `struct file', one per file.
  223.    `nfiles' is the number of elements space has been allocated for.
  224.    `files_index' is the number actually in use.  */
  225.  
  226. /* Address of block containing the files that are described.  */
  227.  
  228. struct file *files;
  229.  
  230. /* Length of block that `files' points to, measured in files.  */
  231.  
  232. int nfiles;
  233.  
  234. /* Index of first unused in `files'.  */
  235.  
  236. int files_index;
  237.  
  238. /* Record of one pending directory waiting to be listed.  */
  239.  
  240. struct pending
  241. {
  242.   char *name;
  243.   /* If the directory is actually the file pointed to by a symbolic link we
  244.      were told to list, `realname' will contain the name of the symbolic
  245.      link, otherwise zero. */
  246.   char *realname;
  247.   struct pending *next;
  248. };
  249.  
  250. struct pending *pending_dirs;
  251.  
  252. /* Current time (seconds since 1970).  When we are printing a file's time,
  253.    include the year if it is more than 6 months before this time.  */
  254.  
  255. long current_time;
  256.  
  257. /* The number of digits to use for block sizes.
  258.    4, or more if needed for bigger numbers.  */
  259.  
  260. int block_size_size;
  261.  
  262. /* The name the program was run with, stripped of any leading path. */
  263. char *program_name;
  264.  
  265. /* Option flags */
  266.  
  267. /* long_format for lots of info, one per line.
  268.    one_per_line for just names, one per line.
  269.    many_per_line for just names, many per line, sorted vertically.
  270.    horizontal for just names, many per line, sorted horizontally.
  271.    with_commas for just names, many per line, separated by commas.
  272.  
  273.    -l, -1, -C, -x and -m control this parameter.  */
  274.  
  275. enum format
  276. {
  277.   long_format,            /* -l */
  278.   one_per_line,            /* -1 */
  279.   many_per_line,        /* -C */
  280.   horizontal,            /* -x */
  281.   with_commas            /* -m */
  282. };
  283.  
  284. enum format format;
  285.  
  286. /* Type of time to print or sort by.  Controlled by -c and -u.  */
  287.  
  288. enum time_type
  289. {
  290.   time_mtime,            /* default */
  291.   time_ctime,            /* -c */
  292.   time_atime            /* -u */
  293. };
  294.  
  295. enum time_type time_type;
  296.  
  297. /* The file characteristic to sort by.  Controlled by -t, -S, and -U. */
  298.  
  299. enum sort_type
  300. {
  301.   sort_none,            /* -U */
  302.   sort_name,            /* default */
  303.   sort_time,            /* -t */
  304.   sort_size            /* -S */
  305. };
  306.  
  307. enum sort_type sort_type;
  308.  
  309. /* Direction of sort.
  310.    0 means highest first if numeric,
  311.    lowest first if alphabetic;
  312.    these are the defaults.
  313.    1 means the opposite order in each case.  -r  */
  314.  
  315. int sort_reverse;
  316.  
  317. /* Nonzero means print the user and group id's as numbers rather
  318.    than as names.  -n  */
  319.  
  320. int numeric_users;
  321.  
  322. /* Nonzero means mention the size in 512 byte blocks of each file.  -s  */
  323.  
  324. int print_block_size;
  325.  
  326. /* Nonzero means show file sizes in kilobytes instead of blocks
  327.    (the size of which is system-dependant).  -k */
  328.  
  329. int kilobyte_blocks;
  330.  
  331. /* none means don't mention the type of files.
  332.    all means mention the types of all files.
  333.    not_programs means do so except for executables.
  334.  
  335.    Controlled by -F and -p.  */
  336.  
  337. enum indicator_style
  338. {
  339.   none,                /* default */
  340.   all,                /* -F */
  341.   not_programs            /* -p */
  342. };
  343.  
  344. enum indicator_style indicator_style;
  345.  
  346. /* Nonzero means mention the inode number of each file.  -i  */
  347.  
  348. int print_inode;
  349.  
  350. /* Nonzero means when a symbolic link is found, display info on
  351.    the file linked to.  -L  */
  352.  
  353. int trace_links;
  354.  
  355. /* Nonzero means when a directory is found, display info on its
  356.    contents.  -R  */
  357.  
  358. int trace_dirs;
  359.  
  360. /* Nonzero means when an argument is a directory name, display info
  361.    on it itself.  -d  */
  362.  
  363. int immediate_dirs;
  364.  
  365. /* Nonzero means don't omit files whose names start with `.'.  -A */
  366.  
  367. int all_files;
  368.  
  369. /* Nonzero means don't omit files `.' and `..'
  370.    This flag implies `all_files'.  -a  */
  371.  
  372. int really_all_files;
  373.  
  374. /* A linked list of shell-style globbing patterns.  If a non-argument
  375.    file name matches any of these patterns, it is omitted.
  376.    Controlled by -I.  Multiple -I options accumulate.
  377.    The -B option adds `*~' and `.*~' to this list.  */
  378.  
  379. struct ignore_pattern
  380. {
  381.   char *pattern;
  382.   struct ignore_pattern *next;
  383. };
  384.  
  385. struct ignore_pattern *ignore_patterns;
  386.  
  387. /* Nonzero means quote nongraphic chars in file names.  -b  */
  388.  
  389. int quote_funny_chars;
  390.  
  391. /* Nonzero means output nongraphic chars in file names as `?'.  -q  */
  392.  
  393. int qmark_funny_chars;
  394.  
  395. /* Nonzero means output each file name using C syntax for a string.
  396.    Always accompanied by `quote_funny_chars'.
  397.    This mode, together with -x or -C or -m,
  398.    and without such frills as -F or -s,
  399.    is guaranteed to make it possible for a program receiving
  400.    the output to tell exactly what file names are present.  -Q  */
  401.  
  402. int quote_as_string;
  403.  
  404. /* The number of chars per hardware tab stop.  -T */
  405. int tabsize;
  406.  
  407. /* Nonzero means we are listing the working directory because no
  408.    non-option arguments were given. */
  409.  
  410. int dir_defaulted;
  411.  
  412. /* Nonzero means print each directory name before listing it. */
  413.  
  414. int print_dir_name;
  415.  
  416. /* The line length to use for breaking lines in many-per-line format.
  417.    Can be set with -w.  */
  418.  
  419. int line_length;
  420.  
  421. /* If nonzero, the file listing format requires that stat be called on
  422.    each file. */
  423.  
  424. int format_needs_stat;
  425.  
  426. void
  427. main (argc, argv)
  428.      int argc;
  429.      char **argv;
  430. {
  431.   register int i;
  432.   register struct pending *thispend;
  433.  
  434.   dir_defaulted = 1;
  435.   print_dir_name = 1;
  436.   pending_dirs = 0;
  437.   current_time = time ((long *) 0);
  438.  
  439.   program_name = argv[0];
  440. #ifdef MSDOS
  441.   strlwr (program_name);
  442. #endif /* not MSDOS */
  443.   i = decode_switches (argc, argv);
  444.  
  445.   format_needs_stat = sort_type == sort_time || sort_type == sort_size
  446.     || format == long_format
  447.     || trace_links || trace_dirs || indicator_style != none
  448.     || print_block_size || print_inode;
  449.  
  450.   nfiles = 100;
  451.   files = (struct file *) xmalloc (sizeof (struct file) * nfiles);
  452.   files_index = 0;
  453.  
  454.   clear_files ();
  455.  
  456.   if (i < argc)
  457.     dir_defaulted = 0;
  458. #ifdef MSDOS
  459.   for (; i < argc; i++)
  460.     {
  461.       int len = strlen (argv[i]);
  462.  
  463.       strlwr (argv[i]);
  464.  
  465.       if (len == 2 && argv[i][1] == ':')    /* cwd on another drive! */
  466.     {
  467.       char *temp = (char *) xmalloc (4);
  468.       strcpy (temp, argv[i]);        /* copy drive  */
  469.       strcat (temp, ".");            /* append `.' */
  470.       argv[i] = temp;
  471.     }
  472.  
  473.       gobble_file ( argv[i], 1, "");
  474.     }
  475. #else
  476.   for (; i < argc; i++)
  477.     gobble_file (argv[i], 1, "");
  478. #endif /* MSDOS */
  479.  
  480.   if (dir_defaulted)
  481.     {
  482.       if (immediate_dirs)
  483.     gobble_file (".", 1, "");
  484.       else
  485.     queue_directory (".", 0);
  486.     }
  487.  
  488.   if (files_index)
  489.     {
  490.       sort_files ();
  491.       if (!immediate_dirs)
  492.     extract_dirs_from_files ("", 0);
  493.       /* `files_index' might be zero now.  */
  494.     }
  495.   if (files_index)
  496.     {
  497.       print_current_files ();
  498.       if (pending_dirs)
  499.     putchar ('\n');
  500.     }
  501.   else if (pending_dirs && pending_dirs->next == 0)
  502.     print_dir_name = 0;
  503.  
  504.   while (pending_dirs)
  505.     {
  506.       thispend = pending_dirs;
  507.       pending_dirs = pending_dirs->next;
  508.       print_dir (thispend->name, thispend->realname);
  509.       free (thispend->name);
  510.       if (thispend->realname)
  511.     free (thispend->realname);
  512.       free (thispend);
  513.       print_dir_name = 1;
  514.     }
  515.  
  516.   exit (0);
  517. }
  518.  
  519. struct option long_options[] =
  520. {
  521.   {"all", 0, 0, 'a'},
  522.   {"escape", 0, 0, 'b'},
  523.   {"directory", 0, 0, 'd'},
  524.   {"inode", 0, 0, 'i'},
  525.   {"kilobyte-file-size", 0, 0, 'k'},
  526.   {"numeric-uid-gid", 0, 0, 'n'},
  527.   {"hide-control-chars", 0, 0, 'q'},
  528.   {"reverse", 0, 0, 'r'},
  529.   {"size", 0, 0, 's'},
  530.   {"width", 1, 0, 'w'},
  531.   {"almost-all", 0, 0, 'A'},
  532.   {"ignore-backups", 0, 0, 'B'},
  533.   {"classify", 0, 0, 'F'},
  534.   {"file-type", 0, 0, 'F'},
  535.   {"ignore", 1, 0, 'I'},
  536.   {"dereference", 0, 0, 'L'},
  537.   {"literal", 0, 0, 'N'},
  538.   {"quote-name", 0, 0, 'Q'},
  539.   {"recursive", 0, 0, 'R'},
  540.   {"format", 1, 0, 12},
  541.   {"sort", 1, 0, 10},
  542.   {"tabsize", 1, 0, 'T'},
  543.   {"time", 1, 0, 11},
  544.   {0, 0, 0, 0}
  545. };
  546.  
  547. char *format_args[] =
  548. {
  549.   "verbose", "long", "commas", "horizontal", "across",
  550.   "vertical", "single-column", 0
  551. };
  552.  
  553. enum format formats[] =
  554. {
  555.   long_format, long_format, with_commas, horizontal, horizontal,
  556.   many_per_line, one_per_line
  557. };
  558.  
  559. char *sort_args[] =
  560. {
  561.   "none", "time", "size", 0
  562. };
  563.  
  564. enum sort_type sort_types[] =
  565. {
  566.   sort_none, sort_time, sort_size
  567. };
  568.  
  569. char *time_args[] =
  570. {
  571.   "access", "use", "status", 0
  572. };
  573.  
  574. enum time_type time_types[] =
  575. {
  576.   time_atime, time_atime, time_ctime
  577. };
  578.  
  579. /* Set all the option flags according to the switches specified.
  580.    Return the index of the first non-option argument.  */
  581.  
  582. int
  583. decode_switches (argc, argv)
  584.      int argc;
  585.      char **argv;
  586. {
  587.   register char *p;
  588.   int c;
  589.   int longind;
  590.  
  591.   qmark_funny_chars = 0;
  592.   quote_funny_chars = 0;
  593.  
  594.   /* initialize all switches to default settings */
  595.  
  596. #ifdef MULTI_COL
  597. #define PROGNAME "dir"
  598.   /* This is for the `dir' program.  */
  599.   format = many_per_line;
  600.   quote_funny_chars = 1;
  601. #else
  602. #ifdef LONG_FORMAT
  603. #define PROGNAME "vdir"
  604.   /* This is for the `vdir' program.  */
  605.   format = long_format;
  606.   quote_funny_chars = 1;
  607. #else
  608. #define PROGNAME "ls"
  609.   /* This is for the `ls' program.  */
  610.   if (isatty (1))
  611.     {
  612.       format = many_per_line;
  613.       qmark_funny_chars = 1;
  614.     }
  615.   else
  616.     {
  617.       format = one_per_line;
  618.       qmark_funny_chars = 0;
  619.     }
  620. #endif
  621. #endif
  622.  
  623.   time_type = time_mtime;
  624.   sort_type = sort_name;
  625.   sort_reverse = 0;
  626.   numeric_users = 0;
  627.   print_block_size = 0;
  628.   kilobyte_blocks = 0;
  629.   indicator_style = none;
  630.   print_inode = 0;
  631.   trace_links = 0;
  632.   trace_dirs = 0;
  633.   immediate_dirs = 0;
  634.   all_files = 0;
  635.   really_all_files = 0;
  636.   ignore_patterns = 0;
  637.   quote_as_string = 0;
  638.  
  639.   p = getenv ("COLUMNS");
  640.   line_length = p ? atoi (p) : 80;
  641.  
  642. #ifdef TIOCGWINSZ
  643.   {
  644.     struct winsize ws;
  645.  
  646.     if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
  647.       line_length = ws.ws_col;
  648.   }
  649. #endif
  650.  
  651.   p = getenv ("TABSIZE");
  652.   tabsize = p ? atoi (p) : 8;
  653.  
  654.   while ((c = getopt_long (argc, argv, "abcdgiklmnpqrstuw:xABCFI:LNQRST:U1",
  655.                long_options, &longind)) != EOF)
  656.     {
  657.       if (c == 0)
  658.     c = long_options[longind].val;
  659.       switch (c)
  660.     {
  661.     case 'a':
  662.       all_files = 1;
  663.       really_all_files = 1;
  664.       break;
  665.       
  666.     case 'b':
  667.       quote_funny_chars = 1;
  668.       qmark_funny_chars = 0;
  669.       break;
  670.       
  671.     case 'c':
  672.       time_type = time_ctime;
  673.       break;
  674.       
  675.     case 'd':
  676.       immediate_dirs = 1;
  677.       break;
  678.       
  679.     case 'g':
  680.       /* No effect.  For BSD compatibility. */
  681.       break;
  682.  
  683.     case 'i':
  684.       print_inode = 1;
  685.       break;
  686.       
  687.     case 'k':
  688.       kilobyte_blocks = 1;
  689.       break;
  690.       
  691.     case 'l':
  692.       format = long_format;
  693.       break;
  694.       
  695.     case 'm':
  696.       format = with_commas;
  697.       break;
  698.       
  699.     case 'n':
  700.       numeric_users = 1;
  701.       break;
  702.       
  703.     case 'p':
  704.       indicator_style = not_programs;
  705.       break;
  706.       
  707.     case 'q':
  708.       qmark_funny_chars = 1;
  709.       quote_funny_chars = 0;
  710.       break;
  711.       
  712.     case 'r':
  713.       sort_reverse = 1;
  714.       break;
  715.       
  716.     case 's':
  717.       print_block_size = 1;
  718.       break;
  719.       
  720.     case 't':
  721.       sort_type = sort_time;
  722.       break;
  723.       
  724.     case 'u':
  725.       time_type = time_atime;
  726.       break;
  727.       
  728.     case 'w':
  729.       line_length = atoi (optarg);
  730.       if (line_length < 1)
  731.         error (1, 0, "invalid line width: %s", optarg);
  732.       break;
  733.       
  734.     case 'x':
  735.       format = horizontal;
  736.       break;
  737.       
  738.     case 'A':
  739.       all_files = 1;
  740.       break;
  741.       
  742.     case 'B':
  743.       add_ignore_pattern ("*~");
  744.       add_ignore_pattern (".*~");
  745.       break;
  746.       
  747.     case 'C':
  748.       format = many_per_line;
  749.       break;
  750.       
  751.     case 'F':
  752.       indicator_style = all;
  753.       break;
  754.       
  755.     case 'I':
  756.       add_ignore_pattern (optarg);
  757.       break;
  758.       
  759.     case 'L':
  760.       trace_links = 1;
  761.       break;
  762.       
  763.     case 'N':
  764.       quote_funny_chars = 0;
  765.       qmark_funny_chars = 0;
  766.       break;
  767.       
  768.     case 'Q':
  769.       quote_as_string = 1;
  770.       quote_funny_chars = 1;
  771.       qmark_funny_chars = 0;
  772.       break;
  773.       
  774.     case 'R':
  775.       trace_dirs = 1;
  776.       break;
  777.       
  778.     case 'S':
  779.       sort_type = sort_size;
  780.       break;
  781.       
  782.     case 'T':
  783.       tabsize = atoi (optarg);
  784.       if (tabsize < 1)
  785.         error (1, 0, "invalid tab size: %s", optarg);
  786.       break;
  787.  
  788.     case 'U':
  789.       sort_type = sort_none;
  790.       break;
  791.  
  792.     case '1':
  793.       format = one_per_line;
  794.       break;
  795.       
  796.     case 10:        /* +sort */
  797.       longind = argmatch (optarg, sort_args);
  798.       if (longind < 0)
  799.         {
  800.           invalid_arg ("sort type", optarg, longind);
  801.           usage ();
  802.         }
  803.       sort_type = sort_types[longind];
  804.       break;
  805.  
  806.     case 11:        /* +time */
  807.       longind = argmatch (optarg, time_args);
  808.       if (longind < 0)
  809.         {
  810.           invalid_arg ("time type", optarg, longind);
  811.           usage ();
  812.         }
  813.       time_type = time_types[longind];
  814.       break;
  815.  
  816.     case 12:        /* +format */
  817.       longind = argmatch (optarg, format_args);
  818.       if (longind < 0)
  819.         {
  820.           invalid_arg ("format type", optarg, longind);
  821.           usage ();
  822.         }
  823.       format = formats[longind];
  824.       break;
  825.       
  826.     default:
  827.       usage ();
  828.     }
  829.     }
  830.  
  831.   return optind;
  832. }
  833.  
  834. /* Request that the directory named `name' have its contents listed later.
  835.    If `realname' is nonzero, it will be used instead of `name' when the
  836.    directory name is printed.  This allows symbolic links to directories
  837.    to be treated as regular directories but still be listed under their
  838.    real names. */
  839.  
  840. void
  841. queue_directory (name, realname)
  842.      char *name;
  843.      char *realname;
  844. {
  845.   struct pending *new;
  846.  
  847.   new = (struct pending *) xmalloc (sizeof (struct pending));
  848.   new->next = pending_dirs;
  849.   pending_dirs = new;
  850.   new->name = copystring (name);
  851.   if (realname)
  852.     new->realname = copystring (realname);
  853.   else
  854.     new->realname = 0;
  855. }
  856.  
  857. /* Read directory `name', and list the files in it.
  858.    If `realname' is nonzero, print its name instead of `name';
  859.    this is used for symbolic links to directories. */
  860.  
  861. void
  862. print_dir (name, realname)
  863.      char *name;
  864.      char *realname;
  865. {
  866.   register DIR *reading;
  867.   register struct direct *next;
  868.   register int total_blocks = 0;
  869.  
  870.   errno = 0;
  871.   reading = opendir (name);
  872.   if (!reading)
  873.     {
  874.       error (0, errno, "%s", name);
  875.       return;
  876.     }
  877.  
  878.   /* Read the directory entries, and insert the subfiles into the `files'
  879.      table.  */
  880.  
  881.   clear_files ();
  882.  
  883.   while (next = readdir (reading))
  884.     if (file_interesting (next))
  885.       total_blocks += gobble_file (next->d_name, 0, name);
  886.  
  887.   closedir (reading);
  888.  
  889.   /* Sort the directory contents.  */
  890.   sort_files ();
  891.  
  892.   /* If any member files are subdirectories, perhaps they should have their
  893.      contents listed rather than being mentioned here as files.  */
  894.  
  895.   if (trace_dirs)
  896.     extract_dirs_from_files (name, 1);
  897.  
  898.   if (print_dir_name)
  899.     {
  900.       if (realname)
  901.     printf ("%s:\n", realname);
  902.       else
  903.     printf ("%s:\n", name);
  904.     }
  905.  
  906.   if (format == long_format || print_block_size)
  907.     printf ("total %u\n", total_blocks);
  908.  
  909.   if (files_index)
  910.     print_current_files ();
  911.  
  912.   if (pending_dirs)
  913.     putchar ('\n');
  914. }
  915.  
  916. /* Add `pattern' to the list of patterns for which files that match are
  917.    not listed.  */
  918.  
  919. void
  920. add_ignore_pattern (pattern)
  921.      char *pattern;
  922. {
  923.   register struct ignore_pattern *ignore;
  924.  
  925.   ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
  926.   ignore->pattern = pattern;
  927.   /* Add it to the head of the linked list. */
  928.   ignore->next = ignore_patterns;
  929.   ignore_patterns = ignore;
  930. }
  931.  
  932. /* Return nonzero if the file in `next' should be listed. */
  933.  
  934. int
  935. file_interesting (next)
  936.      register struct direct *next;
  937. {
  938.   register struct ignore_pattern *ignore;
  939.  
  940.   for (ignore = ignore_patterns; ignore; ignore = ignore->next)
  941.     if (glob_match (ignore->pattern, next->d_name, 1))
  942.       return 0;
  943.  
  944.   if (really_all_files
  945.       || next->d_name[0] != '.'
  946.       || (all_files
  947.       && next->d_name[1] != '\0'
  948.       && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
  949.     return 1;
  950.  
  951.   return 0;
  952. }
  953.  
  954. /* Enter and remove entries in the table `files'.  */
  955.  
  956. /* Empty the table of files. */
  957.  
  958. void
  959. clear_files ()
  960. {
  961.   register int i;
  962.  
  963.   for (i = 0; i < files_index; i++)
  964.     {
  965.       free (files[i].name);
  966.       if (files[i].linkname)
  967.     free (files[i].linkname);
  968.     }
  969.  
  970.   files_index = 0;
  971.   block_size_size = 4;
  972. }
  973.  
  974. /* Add a file to the current table of files.
  975.    Verify that the file exists, and print an error message if it does not.
  976.    Return the number of blocks that the file occupies.  */
  977.  
  978. int
  979. gobble_file (name, explicit_arg, dirname)
  980.      char *name;
  981.      int explicit_arg;
  982.      char *dirname;
  983. {
  984.   register int blocks;
  985.   register int val;
  986.   register char *path;
  987.  
  988.   if (files_index == nfiles)
  989.     {
  990.       nfiles *= 2;
  991.       files = (struct file *) xrealloc ((char *) files, \
  992.                     sizeof (struct file) * nfiles);
  993.     }
  994.  
  995.   files[files_index].linkname = 0;
  996.   files[files_index].linkmode = 0;
  997.  
  998.   if (explicit_arg || format_needs_stat)
  999.     {
  1000.       /* `path' is the absolute pathname of this file. */
  1001.  
  1002.       if (name[0] == '/' || dirname[0] == 0)
  1003.     path = name;
  1004.       else
  1005.     {
  1006.       path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
  1007.       attach (path, dirname, name);
  1008.     }
  1009.  
  1010.       if (trace_links)
  1011.     {
  1012.       val = stat (path, &files[files_index].stat);
  1013.       if (val < 0)
  1014.         /* Perhaps a symbolically-linked to file doesn't exist; stat
  1015.            the link instead. */
  1016.         val = lstat (path, &files[files_index].stat);
  1017.     }
  1018.       else
  1019.     val = lstat (path, &files[files_index].stat);
  1020.       if (val < 0)
  1021.     {
  1022.       error (0, errno, "%s", path);
  1023.       return 0;
  1024.     }
  1025.  
  1026. #ifdef S_IFLNK
  1027.       if ((files[files_index].stat.st_mode & S_IFMT) == S_IFLNK)
  1028.     {
  1029.       char *linkpath;
  1030.       struct stat linkstats;
  1031.  
  1032.       get_link_name (path, &files[files_index]);
  1033.       linkpath = make_link_path (path, files[files_index].linkname);
  1034.  
  1035.       /* Stat the file linked to; automatically trace it in non-long
  1036.          listings, get its mode for the filetype indicator in long
  1037.          listings. */
  1038.       if (linkpath && lstat (linkpath, &linkstats) == 0)
  1039.         {
  1040.           if ((linkstats.st_mode & S_IFMT) == S_IFDIR
  1041.           && explicit_arg && format != long_format)
  1042.         {
  1043.           char *tempname;
  1044.  
  1045.           /* Symbolic links to directories that are mentioned on the
  1046.              command line are automatically traced if not being
  1047.              listed as files. */
  1048.           if (!immediate_dirs)
  1049.             {
  1050.               tempname = name;
  1051.               name = linkpath;
  1052.               linkpath = files[files_index].linkname;
  1053.               files[files_index].linkname = tempname;
  1054.             }
  1055.           files[files_index].stat = linkstats;
  1056.         }
  1057.           else
  1058.         files[files_index].linkmode = linkstats.st_mode;
  1059.         }
  1060.       if (linkpath)
  1061.         free (linkpath);
  1062.     }
  1063. #endif
  1064.  
  1065.       switch (files[files_index].stat.st_mode & S_IFMT)
  1066.     {
  1067. #ifdef S_IFLNK
  1068.     case S_IFLNK:
  1069.       files[files_index].filetype = symbolic_link;
  1070.       break;
  1071. #endif
  1072.  
  1073.     case S_IFDIR:
  1074.       if (explicit_arg && !immediate_dirs)
  1075.         files[files_index].filetype = arg_directory;
  1076.       else
  1077.         files[files_index].filetype = directory;
  1078.       break;
  1079.  
  1080.     default:
  1081.       files[files_index].filetype = normal;
  1082.       break;
  1083.     }
  1084.  
  1085.       blocks = convert_blocks (ST_NBLOCKS (files[files_index].stat),
  1086.                    kilobyte_blocks);
  1087.       if (blocks >= 10000 && block_size_size < 5)
  1088.     block_size_size = 5;
  1089. #ifndef MSDOS
  1090.       if (blocks >= 100000 && block_size_size < 6)
  1091.     block_size_size = 6;
  1092.       if (blocks >= 1000000 && block_size_size < 7)
  1093.     block_size_size = 7;
  1094. #endif /* not MSDOS */
  1095.     }
  1096.   else
  1097.     blocks = 0;
  1098.  
  1099.   files[files_index].name = copystring (name);
  1100.   files_index++;
  1101.  
  1102.   return blocks;
  1103. }
  1104.  
  1105. #ifdef S_IFLNK
  1106.  
  1107. /* Put the name of the file that `filename' is a symbolic link to
  1108.    into the `linkname' field of `f'. */
  1109.  
  1110. void
  1111. get_link_name (filename, f)
  1112.      char *filename;
  1113.      struct file *f;
  1114. {
  1115.   register char *linkbuf;
  1116.   register int bufsiz = f->stat.st_size;
  1117.  
  1118.   linkbuf = (char *) xmalloc (bufsiz + 1);
  1119.   linkbuf[bufsiz] = 0;
  1120.   if (readlink (filename, linkbuf, bufsiz) < 0)
  1121.     {
  1122.       error (0, errno, "%s", filename);
  1123.       free (linkbuf);
  1124.     }
  1125.   else
  1126.     f->linkname = linkbuf;
  1127. }
  1128.  
  1129. /* If `linkname' is a relative path and `path' contains one or more
  1130.    leading directories, return `linkname' with those directories
  1131.    prepended; otherwise, return a copy of `linkname'.
  1132.    If `linkname' is zero, return zero. */
  1133.  
  1134. char *
  1135. make_link_path (path, linkname)
  1136.      char *path;
  1137.      char *linkname;
  1138. {
  1139.   char *linkbuf;
  1140.   int bufsiz;
  1141.  
  1142.   if (linkname == 0)
  1143.     return 0;
  1144.  
  1145.   if (*linkname == '/')
  1146.     return copystring (linkname);
  1147.  
  1148.   /* The link is to a relative path.  Prepend any leading path
  1149.      in `path' to the link name. */
  1150.   linkbuf = rindex (path, '/');
  1151.   if (linkbuf == 0)
  1152.     return copystring (linkname);
  1153.  
  1154.   bufsiz = linkbuf - path + 1;
  1155.   linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
  1156.   strncpy (linkbuf, path, bufsiz);
  1157.   strcpy (linkbuf + bufsiz, linkname);
  1158.   return linkbuf;
  1159. }
  1160. #endif
  1161.  
  1162. /* Remove any entries from `files' that are for directories,
  1163.    and queue them to be listed as directories instead.
  1164.    `dirname' is the prefix to prepend to each dirname
  1165.    to make it correct relative to ls's working dir.
  1166.    `recursive' is nonzero if we should not treat `.' and `..' as dirs.
  1167.    This is desirable when processing directories recursively.  */
  1168.  
  1169. void
  1170. extract_dirs_from_files (dirname, recursive)
  1171.      char *dirname;
  1172.      int recursive;
  1173. {
  1174.   register int i, j;
  1175.   register char *path;
  1176.   int dirlen;
  1177.  
  1178.   dirlen = strlen (dirname) + 2;
  1179.   /* Queue the directories last one first, because queueing reverses the
  1180.      order.  */
  1181.   for (i = files_index - 1; i >= 0; i--)
  1182.     if ((files[i].filetype == directory || files[i].filetype == arg_directory)
  1183.     && (!recursive || is_not_dot_or_dotdot (files[i].name)))
  1184.       {
  1185.     if (files[i].name[0] == '/' || dirname[0] == 0)
  1186.       {
  1187.         queue_directory (files[i].name, files[i].linkname);
  1188.       }
  1189.     else
  1190.       {
  1191.         path = (char *) xmalloc (strlen (files[i].name) + dirlen);
  1192.         attach (path, dirname, files[i].name);
  1193.         queue_directory (path, files[i].linkname);
  1194.         free (path);
  1195.       }
  1196.     if (files[i].filetype == arg_directory)
  1197.       free (files[i].name);
  1198.       }
  1199.  
  1200.   /* Now delete the directories from the table, compacting all the remaining
  1201.      entries.  */
  1202.  
  1203.   for (i = 0, j = 0; i < files_index; i++)
  1204.     if (files[i].filetype != arg_directory)
  1205.       files[j++] = files[i];
  1206.   files_index = j;
  1207. }
  1208.  
  1209. /* Return non-zero if `name' doesn't end in `.' or `..'
  1210.    This is so we don't try to recurse on `././././. ...' */
  1211.  
  1212. int
  1213. is_not_dot_or_dotdot (name)
  1214.      char *name;
  1215. {
  1216.   char *t;
  1217.  
  1218.   t = rindex (name, '/');
  1219.   if (t)
  1220.     name = t + 1;
  1221.  
  1222.   if (name[0] == '.'
  1223.       && (name[1] == '\0'
  1224.       || (name[1] == '.' && name[2] == '\0')))
  1225.     return 0;
  1226.  
  1227.   return 1;
  1228. }
  1229.  
  1230. /* Sort the files now in the table.  */
  1231.  
  1232. void
  1233. sort_files ()
  1234. {
  1235.   int (*func) ();
  1236.  
  1237.   switch (sort_type)
  1238.     {
  1239.     case sort_none:
  1240.       return;
  1241.     case sort_time:
  1242.       switch (time_type)
  1243.     {
  1244.     case time_ctime:
  1245.       func = sort_reverse ? rev_cmp_ctime : compare_ctime;
  1246.       break;
  1247.     case time_mtime:
  1248.       func = sort_reverse ? rev_cmp_mtime : compare_mtime;
  1249.       break;
  1250.     case time_atime:
  1251.       func = sort_reverse ? rev_cmp_atime : compare_atime;
  1252.       break;
  1253.     }
  1254.       break;
  1255.     case sort_name:
  1256.       func = sort_reverse ? rev_cmp_name : compare_name;
  1257.       break;
  1258.     case sort_size:
  1259.       func = sort_reverse ? rev_cmp_size : compare_size;
  1260.       break;
  1261.     }
  1262.  
  1263.   qsort (files, files_index, sizeof (struct file), func);
  1264. }
  1265.  
  1266. /* Comparison routines for sorting the files. */
  1267.  
  1268. int
  1269. compare_ctime (file1, file2)
  1270.      struct file *file1, *file2;
  1271. {
  1272.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1273. }
  1274.  
  1275. int
  1276. rev_cmp_ctime (file2, file1)
  1277.      struct file *file1, *file2;
  1278. {
  1279.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1280. }
  1281.  
  1282. int
  1283. compare_mtime (file1, file2)
  1284.      struct file *file1, *file2;
  1285. {
  1286.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1287. }
  1288.  
  1289. int
  1290. rev_cmp_mtime (file2, file1)
  1291.      struct file *file1, *file2;
  1292. {
  1293.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1294. }
  1295.  
  1296. int
  1297. compare_atime (file1, file2)
  1298.      struct file *file1, *file2;
  1299. {
  1300.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1301. }
  1302.  
  1303. int
  1304. rev_cmp_atime (file2, file1)
  1305.      struct file *file1, *file2;
  1306. {
  1307.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1308. }
  1309.  
  1310. int
  1311. compare_size (file1, file2)
  1312.      struct file *file1, *file2;
  1313. {
  1314.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1315. }
  1316.  
  1317. int
  1318. rev_cmp_size (file2, file1)
  1319.      struct file *file1, *file2;
  1320. {
  1321.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1322. }
  1323.  
  1324. int
  1325. compare_name (file1, file2)
  1326.      struct file *file1, *file2;
  1327. {
  1328.   return strcmp (file1->name, file2->name);
  1329. }
  1330.  
  1331. int
  1332. rev_cmp_name (file2, file1)
  1333.      struct file *file1, *file2;
  1334. {
  1335.   return strcmp (file1->name, file2->name);
  1336. }
  1337.  
  1338. /* List all the files now in the table.  */
  1339.  
  1340. void
  1341. print_current_files ()
  1342. {
  1343.   register int i;
  1344.  
  1345.   switch (format)
  1346.     {
  1347.     case one_per_line:
  1348.       for (i = 0; i < files_index; i++)
  1349.     {
  1350.       print_file_name_and_frills (files + i);
  1351.       putchar ('\n');
  1352.     }
  1353.       break;
  1354.  
  1355.     case many_per_line:
  1356.       print_many_per_line ();
  1357.       break;
  1358.  
  1359.     case horizontal:
  1360.       print_horizontal ();
  1361.       break;
  1362.  
  1363.     case with_commas:
  1364.       print_with_commas ();
  1365.       break;
  1366.  
  1367.     case long_format:
  1368.       for (i = 0; i < files_index; i++)
  1369.     {
  1370.       print_long_format (files + i);
  1371.       putchar ('\n');
  1372.     }
  1373.       break;
  1374.     }
  1375. }
  1376.  
  1377. void
  1378. print_long_format (f)
  1379.      struct file *f;
  1380. {
  1381.   char modebuf[20];
  1382.   char timebuf[40];
  1383.   long when;
  1384.  
  1385.   mode_string (f->stat.st_mode, modebuf);
  1386.   modebuf[10] = 0;
  1387.  
  1388.   switch (time_type)
  1389.     {
  1390.     case time_ctime:
  1391.       when = f->stat.st_ctime;
  1392.       break;
  1393.     case time_mtime:
  1394.       when = f->stat.st_mtime;
  1395.       break;
  1396.     case time_atime:
  1397.       when = f->stat.st_atime;
  1398.       break;
  1399.     }
  1400.  
  1401.   strcpy (timebuf, ctime (&when));
  1402.   if (current_time - when > 6L * 30L * 24L * 60L * 60L
  1403.       || current_time - when < 0L)
  1404.     {
  1405.       /* The file is fairly old or in the future.
  1406.      POSIX says the cutoff is 6 months old;
  1407.      approximate this by 6*30 days.
  1408.      Show the year instead of the time of day.  */
  1409.       strcpy (timebuf + 11, timebuf + 19);
  1410.     }
  1411.   timebuf[16] = 0;
  1412.  
  1413.   if (print_inode)
  1414.     printf ("%6u ", f->stat.st_ino);
  1415.  
  1416.   if (print_block_size)
  1417.     printf ("%*u ", block_size_size, convert_blocks (ST_NBLOCKS (f->stat),
  1418.                              kilobyte_blocks));
  1419.  
  1420.   /* The space between the mode and the number of links is the POSIX
  1421.      "optional alternate access method flag". */
  1422.   printf ("%s %3u ", modebuf, f->stat.st_nlink);
  1423.  
  1424.   if (numeric_users)
  1425.     printf ("%-8u ", f->stat.st_uid);
  1426.   else
  1427.     printf ("%-8s ", getuser (f->stat.st_uid));
  1428.  
  1429.   if (numeric_users)
  1430.     printf ("%-8u ", f->stat.st_gid);
  1431.   else
  1432.     printf ("%-8s ", getgroup (f->stat.st_gid));
  1433.  
  1434. #ifdef S_IFBLK
  1435.   if ((f->stat.st_mode & S_IFMT) == S_IFCHR
  1436.       || (f->stat.st_mode & S_IFMT) == S_IFBLK)
  1437. #else /* not S_IFBLK */
  1438.   if ((f->stat.st_mode & S_IFMT) == S_IFCHR)
  1439. #endif /* not S_IFBLK */
  1440.     printf ("%3u, %3u ", major (f->stat.st_rdev), minor (f->stat.st_rdev));
  1441.   else
  1442.     printf ("%8lu ", f->stat.st_size);
  1443.  
  1444.   printf ("%s ", timebuf + 4);
  1445.  
  1446.   print_name_with_quoting (f->name);
  1447.  
  1448.   if (f->filetype == symbolic_link)
  1449.     {
  1450.       if (f->linkname)
  1451.     {
  1452.       fputs (" -> ", stdout);
  1453.       print_name_with_quoting (f->linkname);
  1454.       if (indicator_style != none)
  1455.         print_type_indicator (f->linkmode);
  1456.     }
  1457.     }
  1458.   else if (indicator_style != none)
  1459.     print_type_indicator (f->stat.st_mode);
  1460. }
  1461.  
  1462. void
  1463. print_name_with_quoting (p)
  1464.      register char *p;
  1465. {
  1466.   register unsigned char c;
  1467.  
  1468.   if (quote_as_string)
  1469.     putchar ('"');
  1470.  
  1471.   while (c = *p++)
  1472.     {
  1473.       if (quote_funny_chars)
  1474.     {
  1475.       switch (c)
  1476.         {
  1477.         case '\\':
  1478.           printf ("\\\\");
  1479.           break;
  1480.  
  1481.         case '\n':
  1482.           printf ("\\n");
  1483.           break;
  1484.  
  1485.         case '\b':
  1486.           printf ("\\b");
  1487.           break;
  1488.  
  1489.         case '\r':
  1490.           printf ("\\r");
  1491.           break;
  1492.  
  1493.         case '\t':
  1494.           printf ("\\t");
  1495.           break;
  1496.  
  1497.         case '\f':
  1498.           printf ("\\f");
  1499.           break;
  1500.  
  1501.         case ' ':
  1502.           printf ("\\ ");
  1503.           break;
  1504.  
  1505.         case '"':
  1506.           printf ("\\\"");
  1507.           break;
  1508.  
  1509.         default:
  1510.           if (c > 040 && c < 0177)
  1511.         putchar (c);
  1512.           else
  1513.         printf ("\\%03o", (unsigned int) c);
  1514.         }
  1515.     }
  1516.       else
  1517.     {
  1518.       if (c >= 040 && c < 0177)
  1519.         putchar (c);
  1520.       else if (!qmark_funny_chars)
  1521.         putchar (c);
  1522.       else
  1523.         putchar ('?');
  1524.     }
  1525.     }
  1526.  
  1527.   if (quote_as_string)
  1528.     putchar ('"');
  1529. }
  1530.  
  1531. /* Print the file name of `f' with appropriate quoting.
  1532.    Also print file size, inode number, and filetype indicator character,
  1533.    as requested by switches.  */
  1534.  
  1535. void
  1536. print_file_name_and_frills (f)
  1537.      struct file *f;
  1538. {
  1539.   if (print_inode)
  1540.     printf ("%6u ", f->stat.st_ino);
  1541.  
  1542.   if (print_block_size)
  1543.     printf ("%*u ", block_size_size, convert_blocks (ST_NBLOCKS (f->stat),
  1544.                              kilobyte_blocks));
  1545.  
  1546.   print_name_with_quoting (f->name);
  1547.  
  1548.   if (indicator_style != none)
  1549.     print_type_indicator (f->stat.st_mode);
  1550. }
  1551.  
  1552. void
  1553. print_type_indicator (mode)
  1554.      unsigned int mode;
  1555. {
  1556.   switch (mode & S_IFMT)
  1557.     {
  1558.     case S_IFDIR:
  1559.       putchar ('/');
  1560.       break;
  1561.  
  1562. #ifdef S_IFLNK
  1563.     case S_IFLNK:
  1564.       putchar ('@');
  1565.       break;
  1566. #endif
  1567.  
  1568. #ifdef S_IFIFO
  1569.     case S_IFIFO:
  1570.       putchar ('|');
  1571.       break;
  1572. #endif
  1573.  
  1574. #ifdef S_IFSOCK
  1575.     case S_IFSOCK:
  1576.       putchar ('=');
  1577.       break;
  1578. #endif
  1579.  
  1580.     case S_IFREG:
  1581.       if (indicator_style == all
  1582.       && (mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1583.     putchar ('*');
  1584.       break;
  1585.     }
  1586. }
  1587.  
  1588. int
  1589. length_of_file_name_and_frills (f)
  1590.      struct file *f;
  1591. {
  1592.   register char *p = f->name;
  1593.   register char c;
  1594.   register int len = 0;
  1595.  
  1596.   if (print_inode)
  1597.     len += 7;
  1598.  
  1599.   if (print_block_size)
  1600.     len += 1 + block_size_size;
  1601.  
  1602.   if (quote_as_string)
  1603.     len += 2;
  1604.  
  1605.   while (c = *p++)
  1606.     {
  1607.       if (quote_funny_chars)
  1608.     {
  1609.       switch (c)
  1610.         {
  1611.         case '\\':
  1612.         case '\n':
  1613.         case '\b':
  1614.         case '\r':
  1615.         case '\t':
  1616.         case '\f':
  1617.         case ' ':
  1618.           len += 2;
  1619.           break;
  1620.  
  1621.         case '"':
  1622.           if (quote_as_string)
  1623.         len += 2;
  1624.           else
  1625.         len += 1;
  1626.           break;
  1627.  
  1628.         default:
  1629.           if (c >= 040 && c < 0177)
  1630.         len += 1;
  1631.           else
  1632.         len += 4;
  1633.         }
  1634.     }
  1635.       else
  1636.     len += 1;
  1637.     }
  1638.  
  1639.   if (indicator_style != none)
  1640.     {
  1641.       unsigned filetype = f->stat.st_mode & S_IFMT;
  1642.  
  1643.       if (filetype == S_IFREG)
  1644.     {
  1645.       if (indicator_style == all
  1646.           && (f->stat.st_mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1647.         len += 1;
  1648.     }
  1649. #ifdef MSDOS
  1650.       else if (filetype != S_IFCHR)
  1651. #else /* not MSDOS */
  1652.       else if (filetype != S_IFBLK && filetype != S_IFCHR)
  1653. #endif /* not MSDOS */
  1654.     len += 1;
  1655.     }
  1656.  
  1657.   return len;
  1658. }
  1659.  
  1660. void
  1661. print_many_per_line ()
  1662. {
  1663.   int filesno;            /* Index into files. */
  1664.   int row;            /* Current row. */
  1665.   int max_name_length;        /* Length of longest file name + frills. */
  1666.   int name_length;        /* Length of each file name + frills. */
  1667.   int pos;            /* Current character column. */
  1668.   int cols;            /* Number of files across. */
  1669.   int rows;            /* Maximum number of files down. */
  1670.  
  1671.   /* Compute the maximum file name length.  */
  1672.   max_name_length = 0;
  1673.   for (filesno = 0; filesno < files_index; filesno++)
  1674.     {
  1675.       name_length = length_of_file_name_and_frills (files + filesno);
  1676.       if (name_length > max_name_length)
  1677.     max_name_length = name_length;
  1678.     }
  1679.  
  1680.   /* Allow at least two spaces between names.  */
  1681.   max_name_length += 2;
  1682.  
  1683.   /* Calculate the maximum number of columns that will fit. */
  1684.   cols = line_length / max_name_length;
  1685.   if (cols == 0)
  1686.     cols = 1;
  1687.   /* Calculate the number of rows that will be in each column except possibly
  1688.      for a short column on the right. */
  1689.   rows = files_index / cols + (files_index % cols != 0);
  1690.   /* Recalculate columns based on rows. */
  1691.   cols = files_index / rows + (files_index % rows != 0);
  1692.  
  1693.   for (row = 0; row < rows; row++)
  1694.     {
  1695.       filesno = row;
  1696.       pos = 0;
  1697.       /* Print the next row.  */
  1698.       while (1)
  1699.     {
  1700.       print_file_name_and_frills (files + filesno);
  1701.       name_length = length_of_file_name_and_frills (files + filesno);
  1702.  
  1703.       filesno += rows;
  1704.       if (filesno >= files_index)
  1705.         break;
  1706.  
  1707.       indent (pos + name_length, pos + max_name_length);
  1708.       pos += max_name_length;
  1709.     }
  1710.       putchar ('\n');
  1711.     }
  1712. }
  1713.  
  1714. void
  1715. print_horizontal ()
  1716. {
  1717.   int filesno;
  1718.   int max_name_length;
  1719.   int name_length;
  1720.   int cols;
  1721.   int pos;
  1722.  
  1723.   /* Compute the maximum file name length.  */
  1724.   max_name_length = 0;
  1725.   for (filesno = 0; filesno < files_index; filesno++)
  1726.     {
  1727.       name_length = length_of_file_name_and_frills (files + filesno);
  1728.       if (name_length > max_name_length)
  1729.     max_name_length = name_length;
  1730.     }
  1731.  
  1732.   /* Allow two spaces between names.  */
  1733.   max_name_length += 2;
  1734.  
  1735.   cols = line_length / max_name_length;
  1736.   if (cols == 0)
  1737.     cols = 1;
  1738.  
  1739.   pos = 0;
  1740.   name_length = 0;
  1741.  
  1742.   for (filesno = 0; filesno < files_index; filesno++)
  1743.     {
  1744.       if (filesno != 0)
  1745.     {
  1746.       if (filesno % cols == 0)
  1747.         {
  1748.           putchar ('\n');
  1749.           pos = 0;
  1750.         }
  1751.       else
  1752.         {
  1753.           indent (pos + name_length, pos + max_name_length);
  1754.           pos += max_name_length;
  1755.         }
  1756.     }
  1757.  
  1758.       print_file_name_and_frills (files + filesno);
  1759.  
  1760.       name_length = length_of_file_name_and_frills (files + filesno);
  1761.     }
  1762.   putchar ('\n');
  1763. }
  1764.  
  1765. void
  1766. print_with_commas ()
  1767. {
  1768.   int filesno;
  1769.   int pos, old_pos;
  1770.  
  1771.   pos = 0;
  1772.  
  1773.   for (filesno = 0; filesno < files_index; filesno++)
  1774.     {
  1775.       old_pos = pos;
  1776.  
  1777.       pos += length_of_file_name_and_frills (files + filesno);
  1778.       if (filesno + 1 < files_index)
  1779.     pos += 2;        /* For the comma and space */
  1780.  
  1781.       if (old_pos != 0 && pos >= line_length)
  1782.     {
  1783.       putchar ('\n');
  1784.       pos -= old_pos;
  1785.     }
  1786.  
  1787.       print_file_name_and_frills (files + filesno);
  1788.       if (filesno + 1 < files_index)
  1789.     {
  1790.       putchar (',');
  1791.       putchar (' ');
  1792.     }
  1793.     }
  1794.   putchar ('\n');
  1795. }
  1796.  
  1797. struct userid
  1798. {
  1799.   int uid;
  1800.   char *name;
  1801.   struct userid *next;
  1802. };
  1803.  
  1804. struct userid *user_alist;
  1805.  
  1806. /* Translate `uid' to a login name, with cache.  */
  1807.  
  1808. char *
  1809. getuser (uid)
  1810.      int uid;
  1811. {
  1812.   register struct userid *tail;
  1813.   struct passwd *pwent;
  1814.   char usernum_string[20];
  1815.  
  1816.   for (tail = user_alist; tail; tail = tail->next)
  1817.     if (tail->uid == uid)
  1818.       return tail->name;
  1819.  
  1820.   pwent = getpwuid (uid);
  1821.   tail = (struct userid *) xmalloc (sizeof (struct userid));
  1822.   tail->uid = uid;
  1823.   tail->next = user_alist;
  1824.   if (pwent == 0)
  1825.     {
  1826.       sprintf (usernum_string, "%u", uid);
  1827.       tail->name = copystring (usernum_string);
  1828.     }
  1829.   else
  1830.     tail->name = copystring (pwent->pw_name);
  1831.   user_alist = tail;
  1832.   return tail->name;
  1833. }
  1834.  
  1835. /* We use the same struct as for userids.  */
  1836. struct userid *group_alist;
  1837.  
  1838. /* Translate `gid' to a group name, with cache.  */
  1839.  
  1840. char *
  1841. getgroup (gid)
  1842.      int gid;
  1843. {
  1844.   register struct userid *tail;
  1845.   struct group *grent;
  1846.   char groupnum_string[20];
  1847.  
  1848.   for (tail = group_alist; tail; tail = tail->next)
  1849.     if (tail->uid == gid)
  1850.       return tail->name;
  1851.  
  1852.   grent = getgrgid (gid);
  1853.   tail = (struct userid *) xmalloc (sizeof (struct userid));
  1854.   tail->uid = gid;
  1855.   tail->next = group_alist;
  1856.   if (grent == 0)
  1857.     {
  1858.       sprintf (groupnum_string, "%u", gid);
  1859.       tail->name = copystring (groupnum_string);
  1860.     }
  1861.   else
  1862.     tail->name = copystring (grent->gr_name);
  1863.   group_alist = tail;
  1864.   return tail->name;
  1865. }
  1866.  
  1867. /* Assuming cursor is at position `from', indent up to position `to'.  */
  1868.  
  1869. void
  1870. indent (from, to)
  1871.      int from, to;
  1872. {
  1873.   while (from < to)
  1874.     {
  1875.       if (to / tabsize > from / tabsize)
  1876.     {
  1877.       putchar ('\t');
  1878.       from += tabsize - from % tabsize;
  1879.     }
  1880.       else
  1881.     {
  1882.       putchar (' ');
  1883.       from++;
  1884.     }
  1885.     }
  1886. }
  1887.  
  1888. /* Low level subroutines of general use,
  1889.    not specifically related to the task of listing a directory.  */
  1890.  
  1891. char *
  1892. xrealloc (obj, size)
  1893.      char *obj;
  1894.      int size;
  1895. {
  1896.   char *val = realloc (obj, size);
  1897.  
  1898.   if (!val)
  1899.     error (1, 0, "virtual memory exhausted");
  1900.  
  1901.   return val;
  1902. }
  1903.  
  1904. char *
  1905. xmalloc (size)
  1906.      int size;
  1907. {
  1908.   char *val = malloc (size);
  1909.  
  1910.   if (!val)
  1911.     error (1, 0, "virtual memory exhausted");
  1912.  
  1913.   return val;
  1914. }
  1915.  
  1916. /* Return a newly allocated copy of `string'. */
  1917.  
  1918. char *
  1919. copystring (string)
  1920.      char *string;
  1921. {
  1922.   return strcpy ((char *) xmalloc (strlen (string) + 1), string);
  1923. }
  1924.  
  1925. /* Put `dirname/name' into `dest', handling `.' and `/' properly. */
  1926.  
  1927. void
  1928. attach (dest, dirname, name)
  1929.      char *dest, *dirname, *name;
  1930. {
  1931.   char *dirnamep = dirname;
  1932.  
  1933.   /* Copy dirname if it is not ".". */
  1934.   if (dirname[0] != '.' || dirname[1] != 0)
  1935.     {
  1936.       while (*dirnamep)
  1937.     *dest++ = *dirnamep++;
  1938.       /* Add '/' if `dirname' doesn't already end with it. */
  1939.       if (dirnamep > dirname && dirnamep[-1] != '/')
  1940.     *dest++ = '/';
  1941.     }
  1942.   while (*name)
  1943.     *dest++ = *name++;
  1944.   *dest = 0;
  1945. }
  1946.  
  1947. void
  1948. usage ()
  1949. {
  1950.   fprintf (stderr, "\
  1951. Usage: %s [-abcdgiklmnpqrstuxABCFLNQRSU1] [-w cols] [-T cols] [-I pattern]\n\
  1952.        [+all] [+escape] [+directory] [+inode] [+kilobyte-file-size]\n\
  1953.        [+numeric-uid-gid] [+hide-control-chars] [+reverse] [+size]\n\
  1954.        [+width cols] [+tabsize cols] [+almost-all] [+ignore-backups]\n",
  1955.        program_name);
  1956.   fprintf (stderr, "\
  1957.        [+classify] [+file-type] [+ignore pattern] [+dereference] [+literal]\n\
  1958.        [+quote-name] [+recursive] [+sort {none,time,size}]\n\
  1959.        [+format {long,verbose,commas,across,vertical,single-column}]\n\
  1960.        [+time {access,use,status}] [path...]\n");
  1961.   exit (1);
  1962. }
  1963.